﻿using System;
using System.Text.RegularExpressions;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using KMF.WebUI.App_Start;


namespace KMF.WebUI
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Config.RegisterConfig();
        }

        /// <summary>
        /// Chuyen www.babo.vn sang dang khong co babo.vn
        /// </summary>
        private static readonly Regex wwwRegex =
        new Regex(@"www\.(?<mainDomain>.*)",
                  RegexOptions.Compiled
                      | RegexOptions.IgnoreCase
                      | RegexOptions.Singleline);

        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            string hostName = Request.Headers["x-forwarded-host"];
            hostName = string.IsNullOrEmpty(hostName) ? Request.Url.Host : hostName;
            Match match = wwwRegex.Match(hostName);
            if (match.Success)
            {
                string mainDomain = match.Groups["mainDomain"].Value;
                var builder = new UriBuilder(Request.Url)
                {
                    Host = mainDomain
                };
                string redirectUrl = builder.Uri.ToString();
                Response.Clear();
                Response.StatusCode = 301;
                Response.StatusDescription = "Moved Permanently";
                Response.AddHeader("Location", redirectUrl);
                Response.End();
            }
        }
    }
}